<script setup lang="ts">

import {uploadToken} from "../../api/base.ts";
import axios from "axios";
import {defineEmits, defineProps, ref} from "vue";

const emit = defineEmits(['backKEY'])
const props = defineProps({
    imgName:{
        type:String,
        default:'',
    }
})
// const model = ref({
//     title: '',
//     img: '',
//     url: '',
//     status: null
// })
const imgurl = ref('')
const formRef = ref()
const customRequest= ({file,action,headers,onFinish,onError}) => {
    uploadToken().then(res => {

        // 组装上传的参数
        const formDate = new FormData
        //  随机生成图片名称
        const fileName = `${Date.now()}${Math.floor(Math.random()*1000)}.${file.name.split('.').pop()}`
        console.log(fileName)

        formDate.append('key',fileName)
        formDate.append('OSSAccessKeyId',res.data.accessid)
        formDate.append('policy',res.data.policy)
        formDate.append('Signature',res.data.signature)
        formDate.append('file',file.file)

        axios.post(res.data.host,formDate,{
            headers:{
                'Content-Type':'multipart/form-data'
            }
        }).then(res=>{
            emit('backKEY',fileName)
            imgurl.value= `${res.data.host}/${fileName}`

            formRef.value.validate()
            onFinish(fileName)
        }).catch(err=>{})
    })
}
</script>

<template>
    <n-upload
            :custom-request="customRequest"
            v-model:value="props.imgName"
    >
        <n-button v-if="!imgurl">上传图片</n-button>
        <n-image
                v-else
                width="100"
                :src="imgurl"
                :preview-disabled="true"
        />
    </n-upload>
</template>

<style scoped>

</style>